package com.ipCount;

import javax.servlet.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*
    利用Filter做一个统计各IP访问网站浏览的次数功能
    修改Filter类，在Filter初始化时，初始化一个Map类型，用于存储ip信息和访问次数。
    并且将该map存储至ServletContext中。
 */
public class MyFilter implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化参数，ipCount 用来存放ip及访问次数
        ServletContext servletContext = filterConfig.getServletContext();
        // 创建一个Map集合，用于存放ip地址和访问次数
        Map<String,Integer> ipCount = new HashMap<String,Integer>();
        // 设置一个servletContext全局变量
        servletContext.setAttribute("ipCount",ipCount);
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 设置字符
        servletRequest.setCharacterEncoding("UTF-8");
        servletResponse.setContentType("text/html;Charset=UTF-8");

        //获取IP
        String ip = servletRequest.getRemoteAddr();
        // 获取ServletContext对象
        ServletContext servletContext = servletRequest.getServletContext();
        // 从全局中获取记录IP信息的Map集合
        HashMap<String,Integer> ipCount = (HashMap<String, Integer>) servletContext.getAttribute("ipCount");
        Integer count = ipCount.get(ip);
        if(count != null){
            // Map 中 存在IP
            count = count +1 ;
        }else {
            count = 1;
        }
        ipCount.put(ip,count);
        System.out.println(ipCount);
        servletContext.setAttribute("ipCount",ipCount);
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
